<template>
  <view class="file-manager">
    <u-navbar title="文件管理"></u-navbar>

    <!-- 顶部操作栏 -->
    <view class="toolbar">
      <view class="toolbar-left">
        <u-button size="mini" @click="handleSort">
          {{ sortType === "name" ? "按名称排序" : "按时间排序" }}
          <u-icon
            :name="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'"
            size="24"
          ></u-icon>
        </u-button>
      </view>
      <view class="toolbar-right">
        <u-button size="mini" @click="handleViewMode">
          <u-icon :name="viewMode === 'list' ? 'list' : 'grid'" size="24"></u-icon>
        </u-button>
      </view>
    </view>

    <!-- 文件列表 -->
    <view class="file-list" :class="viewMode">
      <u-cell-group>
        <view v-for="item in sortedFileList" :key="item.name" class="file-item">
          <u-cell-item :title="item.name" @click="handleItemClick(item)">
            <view slot="icon" class="cell-icon">
              <u-icon
                :name="item.isDirectory ? 'folder' : getFileIcon(item.name)"
                :color="item.isDirectory ? '#FFB700' : '#2979ff'"
                size="40"
              ></u-icon>
            </view>
            <view slot="label" v-if="!item.isDirectory">
              {{ formatFileSize(item.size) }} · {{ formatDate(item.lastModified) }}
            </view>
            <view slot="right-icon">
              <u-icon name="more-dot-fill" @click.stop="handleMoreClick(item)"></u-icon>
            </view>
          </u-cell-item>
        </view>
      </u-cell-group>
    </view>

    <!-- 空状态 -->
    <u-empty v-if="sortedFileList.length === 0" mode="data" text="暂无文件"></u-empty>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";

// 定义文件项接口
interface FileItem {
  name: string;
  isDirectory: boolean;
  size?: number;
  lastModified?: number;
  path: string;
}

// 视图模式
const viewMode = ref<"list" | "grid">("list");
// 排序类型
const sortType = ref<"name" | "time">("name");
// 排序顺序
const sortOrder = ref<"asc" | "desc">("asc");

// 文件列表数据
const fileList = ref<FileItem[]>([
  {
    name: "我的文档",
    isDirectory: true,
    path: "/documents",
    lastModified: Date.now(),
  },
  {
    name: "照片",
    isDirectory: true,
    path: "/photos",
    lastModified: Date.now() - 86400000,
  },
  {
    name: "报告.pdf",
    isDirectory: false,
    size: 1024576, // 1MB
    lastModified: Date.now() - 172800000,
    path: "/报告.pdf",
  },
]);

// 排序后的文件列表
const sortedFileList = computed(() => {
  const list = [...fileList.value];
  return list.sort((a, b) => {
    // 文件夹始终在前
    if (a.isDirectory !== b.isDirectory) {
      return a.isDirectory ? -1 : 1;
    }

    // 根据排序类型和顺序进行排序
    const factor = sortOrder.value === "asc" ? 1 : -1;
    if (sortType.value === "name") {
      return a.name.localeCompare(b.name) * factor;
    } else {
      const aTime = a.lastModified || 0;
      const bTime = b.lastModified || 0;
      return (aTime - bTime) * factor;
    }
  });
});

// 处理排序点击
const handleSort = () => {
  if (sortType.value === "name") {
    if (sortOrder.value === "asc") {
      sortOrder.value = "desc";
    } else {
      sortType.value = "time";
      sortOrder.value = "asc";
    }
  } else {
    if (sortOrder.value === "asc") {
      sortOrder.value = "desc";
    } else {
      sortType.value = "name";
      sortOrder.value = "asc";
    }
  }
};

// 处理视图模式切换
const handleViewMode = () => {
  viewMode.value = viewMode.value === "list" ? "grid" : "list";
};

// 处理文件项点击
const handleItemClick = (item: FileItem) => {
  if (item.isDirectory) {
    // TODO: 进入文件夹
    uni.showToast({
      title: `进入文件夹：${item.name}`,
      icon: "none",
    });
  } else {
    // TODO: 预览文件
    uni.showToast({
      title: `预览文件：${item.name}`,
      icon: "none",
    });
  }
};

// 处理更多按钮点击
const handleMoreClick = (item: FileItem) => {
  const actions = ["重命名", "删除"];
  if (!item.isDirectory) {
    actions.push("下载");
  }
  actions.push("详情");

  uni.showActionSheet({
    itemList: actions,
    success: function (res) {
      switch (actions[res.tapIndex]) {
        case "重命名":
          handleRename(item);
          break;
        case "删除":
          handleDelete(item);
          break;
        case "下载":
          handleDownload(item);
          break;
        case "详情":
          handleDetails(item);
          break;
      }
    },
  });
};

// 处理重命名
const handleRename = (item: FileItem) => {
  uni.showModal({
    title: "重命名",
    editable: true,
    placeholderText: "请输入新名称",
    content: item.name,
    success: function (res) {
      if (res.confirm && res.content) {
        // TODO: 实现重命名逻辑
        uni.showToast({
          title: `重命名为：${res.content}`,
          icon: "none",
        });
      }
    },
  });
};

// 处理删除
const handleDelete = (item: FileItem) => {
  uni.showModal({
    title: "确认删除",
    content: `是否确认删除 ${item.name}？`,
    success: function (res) {
      if (res.confirm) {
        // TODO: 实现删除逻辑
        uni.showToast({
          title: "删除成功",
          icon: "success",
        });
      }
    },
  });
};

// 处理下载
const handleDownload = (item: FileItem) => {
  // TODO: 实现下载逻辑
  uni.showToast({
    title: `开始下载：${item.name}`,
    icon: "none",
  });
};

// 处理详情
const handleDetails = (item: FileItem) => {
  uni.showModal({
    title: "文件详情",
    content: `名称：${item.name}\n类型：${item.isDirectory ? "文件夹" : "文件"}\n${
      item.size ? `大小：${formatFileSize(item.size)}\n` : ""
    }修改时间：${formatDate(item.lastModified)}`,
    showCancel: false,
  });
};

// 获取文件图标
const getFileIcon = (fileName: string) => {
  const ext = fileName.split(".").pop()?.toLowerCase();
  switch (ext) {
    case "pdf":
      return "file-text";
    case "jpg":
    case "jpeg":
    case "png":
    case "gif":
      return "image";
    case "doc":
    case "docx":
      return "file-word";
    case "xls":
    case "xlsx":
      return "file-excel";
    default:
      return "file";
  }
};

// 格式化文件大小
const formatFileSize = (size?: number) => {
  if (!size) return "0 B";
  const units = ["B", "KB", "MB", "GB", "TB"];
  let index = 0;
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024;
    index++;
  }
  return `${size.toFixed(2)} ${units[index]}`;
};

// 格式化日期
const formatDate = (timestamp?: number) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(
    date.getDate()
  ).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(
    date.getMinutes()
  ).padStart(2, "0")}`;
};
</script>

<style lang="scss" scoped>
.file-manager {
  min-height: 100vh;
  background-color: #f5f5f5;

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    background-color: #ffffff;

    &-left,
    &-right {
      display: flex;
      align-items: center;
      gap: 20rpx;
    }
  }

  .file-list {
    padding: 10rpx 0;

    &.grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20rpx;
      padding: 20rpx;
    }

    .file-item {
      margin: 10rpx 20rpx;
      background-color: #ffffff;
      border-radius: 10rpx;

      .cell-icon {
        margin-right: 10rpx;
      }
    }
  }
}
</style>
